import { ref } from 'vue'
import { defineStore } from 'pinia'
import { login } from '@/api/user'
import { mergeCartList } from '@/api/cart'
import { useCartStore } from './cart'


export const useUserStore = defineStore('user', () => {
    const cartStore = useCartStore()
    /**
     * 定义数据 state
     */
    const userInfo = ref({})

    /**
     * 定义方法 action
     */
    // 用户登录(获取用户信息)
    const getUserInfo = async (data) => {
        let res = await login(data)
        userInfo.value = res.result
        // 获取购物车列表
        mergeCartList(cartStore.cartList.map(item => {
            return {
                skuId: item.skuId,
                selected: item.selected,
                count: item.count,
            }
        })).then(res => cartStore.getCart())
    }
    
    // 退出登录
    const clearUserInfo = () => {
        userInfo.value = {}
        // 清除购物车列表
        cartStore.clearCartList()
    }

    return { userInfo, getUserInfo, clearUserInfo }
}, {
    // 插件：持久化
    persist: true
})

